package com.wangzhenyu.learn.test.adapter

import android.annotation.SuppressLint
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.wangzhenyu.common.util.log.LogUtil
import com.wangzhenyu.learn.R
import com.wangzhenyu.learn.databinding.ItemFragmentMainOneBinding
import com.wangzhenyu.learn.test.net.OnSellResult

class OnSellListAdapter() : RecyclerView.Adapter<OnSellListAdapter.InnerHolder>() {

    companion object {

        //这个要放在静态代码快里
        @JvmStatic
        @BindingAdapter("goodsImage", "testValue")
        fun setUpImage(iv: ImageView, goodsImage: String?, testValue: String) {
            //加载图片
            if (goodsImage != null) {
                Glide.with(iv.context).load("https:$goodsImage").into(iv)
            } else {
                //设置默认图
            }
        }


        @JvmStatic
        @BindingAdapter("finalPrise")
        fun setUpFinalPrice(textView: TextView, finalPrise: String) {
            val result = String.format(
                textView.context.getString(R.string.test_main_price),
                finalPrise.toFloat()
            )
            //在TextView中加一个中划线
            textView.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            textView.text = result
        }
    }

    private val mContentList by lazy {
        mutableListOf<OnSellResult.MapData?>()
    }

    class InnerHolder(itemView: View, val binding: ItemFragmentMainOneBinding) :
        RecyclerView.ViewHolder(itemView) {

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val viewBinding = DataBindingUtil.inflate<ItemFragmentMainOneBinding>(
            LayoutInflater.from(parent.context),
            R.layout.item_fragment_main_one,
            parent,
            false
        )
        return InnerHolder(viewBinding.root, viewBinding)
    }

    override fun getItemCount() = mContentList.size

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        holder.binding.eventHandler = EventHandler()
        holder.binding.itemData = mContentList[position]
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setData(contentList: List<OnSellResult.MapData?>) {
        mContentList.clear()
        mContentList.addAll(contentList)
        notifyDataSetChanged()
    }

    inner class EventHandler {
        fun onItemClick(itemView: View, title: String?, id: String?) {
            LogUtil.default03("Test $title")
        }


        //这里返回Boolean是因为View.java中的OnLongClickListener接口的抽象方法onLongClick(View v)返回值为Boolean
        fun onItemLongClick(itemView: View): Boolean {
            LogUtil.default03("长按了")
            return true
        }
    }

}